package com.hy.formula.function;

import java.math.BigDecimal;

import com.hy.formula.common.BigDecimalUtils;
import com.hy.formula.common.CollectionUtils;
import com.hy.formula.runtime.FRuntimeContext;


/**
 * 求和
 * @author huangy
 * @date 2015年4月29日 下午9:22:53
 */
public class SumFunc extends AbsNumCalculateFunc implements IFunction {

	
	@Override
	public Object execute(FRuntimeContext context, Object... params) {
		
		if(!CollectionUtils.isEmpty(params)){
			//判断传入的数值中哪个哪个类型比较高级
			boolean floatFlag = false;
			boolean doubleFlag = false;
			boolean bigDecimalFlag = false;
			for(Object obj : params){
				if(obj instanceof BigDecimal) {
					bigDecimalFlag = true;
					break;
				}else if(obj instanceof Double){
					doubleFlag = true;
					break;
				}else if(obj instanceof Float){
					floatFlag = true;
				}
			}
			
			if(bigDecimalFlag) {
				BigDecimal result = BigDecimal.ZERO;
				for(Object param : params) {
					result = BigDecimalUtils.sum(result,new BigDecimal(param.toString()));
				}
				return result;
			}else if(doubleFlag){
				//转成双精度
				double result = 0.0d;
				for(Object param : params){
					String num = param.toString();
					result += Double.parseDouble(num);
				}
				return result;
			}else if(floatFlag){
				//转成浮点数计算
				float result = 0.0f;
				for(Object param : params){
					String num = param.toString();
					result += Float.parseFloat(num);
				}
				return result;
			}else{
				//全部用整型计算
				Integer result = 0;
				for(Object param : params){
					result += (int)param;
				}
				return result;
			}
		}else{
			throw new IllegalArgumentException("请输入参数");
		}
	}

	@Override
	public String description() {
		StringBuilder desc = new StringBuilder();
		desc.append("函数:求和\n")
			.append("参数:多个数值\n");
		return desc.toString();
	}

	@Override
	public String getName() {
		return "sum";
	}
	
}
